using UnityEditor;
using UnityEngine;
using System.IO;
using System.Text;
using System.Linq;
using System;

namespace MagicLib
{
    public class AutoNamespace : AssetModificationProcessor
    {
        // EditorPrefs键名常量
        private const string PREFS_KEY = "MagicLib_AutoNamespace_Enabled";
        
        // 默认启用状态
        private static bool IsEnabled
        {
            get => EditorPrefs.GetBool(PREFS_KEY, true);
            set => EditorPrefs.SetBool(PREFS_KEY, value);
        }

        // 创建新脚本时自动添加命名空间
        public static void OnWillCreateAsset(string path)
        {
            // 检查开关状态
            if (!IsEnabled) return;

            if (!path.EndsWith(".meta")) return;
            string scriptPath = path.Replace(".meta", "");
            if (!scriptPath.EndsWith(".cs")) return;

            try
            {
                string namespaceName = GetProjectName();
                string content = File.ReadAllText(scriptPath, Encoding.UTF8);

                if (content.Contains("namespace")) return;

                int insertionPoint = FindInsertionPoint(content);
                string namespaceStart = $"namespace {namespaceName}\n{{\n";
                string namespaceEnd = "\n}";

                StringBuilder newContent = new StringBuilder(content);
                newContent.Insert(insertionPoint, namespaceStart);
                newContent.Append(namespaceEnd);

                File.WriteAllText(scriptPath, newContent.ToString(), Encoding.UTF8);
                AssetDatabase.Refresh();
            }
            catch (Exception e)
            {
                Debug.LogError($"Failed to add namespace: {e.Message}\n{e.StackTrace}");
            }
        }

        // 查找插入点位置
        private static int FindInsertionPoint(string content)
        {
            int lastUsingIndex = -1;
            int currentIndex = 0;

            while ((currentIndex = content.IndexOf("using ", currentIndex)) != -1)
            {
                lastUsingIndex = content.IndexOf(';', currentIndex) + 1;
                currentIndex = lastUsingIndex;
            }

            if (lastUsingIndex > 0)
            {
                while (lastUsingIndex < content.Length && content[lastUsingIndex] != '\n')
                {
                    lastUsingIndex++;
                }
                return lastUsingIndex + 1;
            }

            int pragmaIndex = content.LastIndexOf("#pragma");
            if (pragmaIndex != -1)
            {
                int pragmaEnd = content.IndexOf('\n', pragmaIndex) + 1;
                return pragmaEnd > 0 ? pragmaEnd : pragmaIndex;
            }

            return 0;
        }

        // 获取项目名称
        private static string GetProjectName()
        {
            string projectPath = Application.dataPath.Replace("/Assets", "");
            string projectName = Path.GetFileName(projectPath);
            return new string(projectName
                .Where(c => char.IsLetterOrDigit(c) || c == '_')
                .ToArray());
        }

        // 开关自动命名空间功能
        private static bool isInitialized = false;
        
        // 菜单项，用于切换自动命名空间功能
        [MenuItem("MagicLib/AutoNamespace", priority = 0)]
        private static void ToggleEnabled()
        {
            if (!isInitialized)
            {
                EditorApplication.update += InitializeOnce;
                isInitialized = true;
            }
            
            IsEnabled = !IsEnabled;
            Debug.Log($"Auto Namespace {(IsEnabled ? "Enabled" : "Disabled")}");
        }

        // 初始化一次，设置菜单项的勾选状态
        private static void InitializeOnce()
        {
            EditorApplication.update -= InitializeOnce;
            EditorApplication.delayCall += () =>
            {
                Menu.SetChecked("MagicLib/AutoNamespace", IsEnabled);
            };
        }

        // 在菜单项旁边显示勾选状态
        [MenuItem("MagicLib/AutoNamespace", true)]
        private static bool ToggleEnabledValidate()
        {
            Menu.SetChecked("MagicLib/AutoNamespace", IsEnabled);
            return true;
        }
    }
}